<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>{{ isEdit ? '编辑预约' : '新增预约' }}</h3>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="100px" 
        v-loading="loading"
      >
        <!-- 患者信息 -->
        <el-divider content-position="left">患者信息</el-divider>
        <el-form-item label="患者" prop="patientId">
          <el-select 
            v-model="form.patientId" 
            filterable 
            placeholder="请选择患者" 
            style="width: 100%"
            remote
            :remote-method="searchPatients"
            :loading="patientLoading"
            @change="handlePatientChange"
          >
            <el-option 
              v-for="item in patientOptions" 
              :key="item._id" 
              :label="`${item.name} (${item.idNumber})`" 
              :value="item._id"
            >
              <div class="option-content">
                <div>{{ item.name }}</div>
                <div class="option-secondary">{{ item.idNumber }} | {{ item.contactInfo?.phone }}</div>
              </div>
            </el-option>
          </el-select>
          <div class="form-tips">如未找到患者，请先 <el-link type="primary" @click="goToCreatePatient">创建新患者</el-link></div>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名">
              <el-input v-model="patientInfo.name" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话">
              <el-input v-model="patientInfo.phone" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 预约信息 -->
        <el-divider content-position="left">预约信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="科室" prop="departmentId">
              <el-select 
                v-model="form.departmentId" 
                placeholder="请选择科室" 
                style="width: 100%"
                @change="handleDepartmentChange"
              >
                <el-option 
                  v-for="item in departments" 
                  :key="item._id" 
                  :label="item.name" 
                  :value="item._id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医生" prop="doctorId">
              <el-select 
                v-model="form.doctorId" 
                placeholder="请选择医生" 
                style="width: 100%"
                @change="handleDoctorChange"
                :disabled="!form.departmentId"
              >
                <el-option 
                  v-for="item in doctors" 
                  :key="item._id" 
                  :label="`${item.name} (${item.title || '医生'})`" 
                  :value="item._id"
                >
                  <div class="option-content">
                    <div>{{ item.name }} - {{ item.title || '医生' }}</div>
                    <div class="option-secondary">{{ item.specialty || '暂无专长信息' }}</div>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预约日期" prop="appointmentDate">
              <el-date-picker
                v-model="form.appointmentDate"
                type="date"
                placeholder="选择预约日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
                :disabled-date="disabledDate"
                @change="handleDateChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="时间段" prop="timeSlot">
              <el-select 
                v-model="form.timeSlot" 
                placeholder="请选择预约时间段" 
                style="width: 100%"
                :disabled="!form.appointmentDate || !form.doctorId"
              >
                <el-option 
                  v-for="item in availableTimeSlots" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="就诊类型" prop="visitType">
          <el-select v-model="form.visitType" placeholder="请选择就诊类型" style="width: 100%">
            <el-option label="初诊" value="初诊" />
            <el-option label="复诊" value="复诊" />
            <el-option label="咨询" value="咨询" />
            <el-option label="急诊" value="急诊" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="就诊原因" prop="visitReason">
          <el-input 
            v-model="form.visitReason" 
            type="textarea" 
            placeholder="请简要描述就诊原因" 
            :rows="3"
          />
        </el-form-item>
        
        <el-form-item label="备注" prop="notes">
          <el-input 
            v-model="form.notes" 
            type="textarea" 
            placeholder="请输入备注信息（可选）" 
            :rows="2"
          />
        </el-form-item>
        
        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { appointmentAPI, patientAPI, departmentAPI, doctorAPI, scheduleAPI } from '@/utils/api'

// 路由实例
const router = useRouter()
const route = useRoute()

// 判断是编辑还是新增
const isEdit = computed(() => route.params.id !== undefined)

// 加载状态
const loading = ref(false)
const submitLoading = ref(false)
const patientLoading = ref(false)

// 表单引用
const formRef = ref(null)

// 表单数据
const form = reactive({
  patientId: '',
  departmentId: '',
  doctorId: '',
  appointmentDate: '',
  timeSlot: '',
  visitType: '初诊',
  visitReason: '',
  notes: ''
})

// 患者信息
const patientInfo = reactive({
  name: '',
  phone: ''
})

// 选项数据
const patientOptions = ref([])
const departments = ref([])
const doctors = ref([])
const availableTimeSlots = ref([])

// 表单验证规则
const rules = {
  patientId: [
    { required: true, message: '请选择患者', trigger: 'change' }
  ],
  departmentId: [
    { required: true, message: '请选择科室', trigger: 'change' }
  ],
  doctorId: [
    { required: true, message: '请选择医生', trigger: 'change' }
  ],
  appointmentDate: [
    { required: true, message: '请选择预约日期', trigger: 'change' }
  ],
  timeSlot: [
    { required: true, message: '请选择预约时间段', trigger: 'change' }
  ],
  visitType: [
    { required: true, message: '请选择就诊类型', trigger: 'change' }
  ],
  visitReason: [
    { required: true, message: '请输入就诊原因', trigger: 'blur' }
  ]
}

// 禁用的日期（过去的日期）
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
}

// 搜索患者
const searchPatients = async (query) => {
  if (!query) return
  patientLoading.value = true
  try {
    const res = await patientAPI.getPatients({
      name: query,
      limit: 10
    })
    patientOptions.value = res.data.items
  } catch (error) {
    console.error('搜索患者失败', error)
  } finally {
    patientLoading.value = false
  }
}

// 处理患者选择变化
const handlePatientChange = async (patientId) => {
  if (!patientId) {
    patientInfo.name = ''
    patientInfo.phone = ''
    return
  }
  
  try {
    const res = await patientAPI.getPatient(patientId)
    const patient = res.data
    patientInfo.name = patient.name
    patientInfo.phone = patient.contactInfo?.phone || ''
  } catch (error) {
    console.error('获取患者信息失败', error)
    ElMessage.error('获取患者信息失败')
  }
}

// 处理科室选择变化
const handleDepartmentChange = async () => {
  form.doctorId = ''
  form.timeSlot = ''
  doctors.value = []
  availableTimeSlots.value = []
  
  if (!form.departmentId) return
  
  try {
    const res = await doctorAPI.getDoctors({ departmentId: form.departmentId })
    doctors.value = res.data.items
  } catch (error) {
    console.error('获取医生列表失败', error)
    ElMessage.error('获取医生列表失败')
  }
}

// 处理医生选择变化
const handleDoctorChange = () => {
  form.timeSlot = ''
  loadAvailableTimeSlots()
}

// 处理日期选择变化
const handleDateChange = () => {
  form.timeSlot = ''
  loadAvailableTimeSlots()
}

// 加载可用时间段
const loadAvailableTimeSlots = async () => {
  availableTimeSlots.value = []
  
  if (!form.doctorId || !form.appointmentDate) return
  
  try {
    // 获取医生当天的排班
    const res = await scheduleAPI.getSchedules({
      doctorId: form.doctorId,
      date: form.appointmentDate
    })
    
    if (res.data.items.length === 0) {
      ElMessage.warning('该医生在所选日期没有排班')
      return
    }
    
    // 获取医生当天的可用时间段
    const schedules = res.data.items
    let timeSlots = []
    
    schedules.forEach(schedule => {
      if (schedule.availableTimeSlots && schedule.availableTimeSlots.length > 0) {
        timeSlots = [...timeSlots, ...schedule.availableTimeSlots.map(slot => ({
          label: slot,
          value: slot
        }))]
      }
    })
    
    availableTimeSlots.value = timeSlots
    
    if (timeSlots.length === 0) {
      ElMessage.warning('该医生在所选日期没有可预约的时间段')
    }
  } catch (error) {
    console.error('获取可用时间段失败', error)
    ElMessage.error('获取可用时间段失败')
  }
}

// 获取科室列表
const getDepartments = async () => {
  try {
    const res = await departmentAPI.getDepartments()
    departments.value = res.data.items
  } catch (error) {
    console.error('获取科室列表失败', error)
    ElMessage.error('获取科室列表失败')
  }
}

// 获取预约详情（编辑模式）
const getAppointmentDetail = async () => {
  loading.value = true
  try {
    const id = route.params.id
    const res = await appointmentAPI.getAppointment(id)
    const appointment = res.data
    
    // 填充表单数据
    Object.keys(form).forEach(key => {
      if (appointment[key] !== undefined) {
        form[key] = appointment[key]
      }
    })
    
    // 获取患者信息
    if (appointment.patientId) {
      handlePatientChange(appointment.patientId)
    }
    
    // 获取医生列表
    if (appointment.departmentId) {
      try {
        const res = await doctorAPI.getDoctors({ departmentId: appointment.departmentId })
        doctors.value = res.data.items
      } catch (error) {
        console.error('获取医生列表失败', error)
      }
    }
    
    // 获取可用时间段
    if (appointment.doctorId && appointment.appointmentDate) {
      loadAvailableTimeSlots()
    }
  } catch (error) {
    console.error('获取预约详情失败', error)
    ElMessage.error('获取预约详情失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (isEdit.value) {
          // 编辑模式
          await appointmentAPI.updateAppointment(route.params.id, form)
          ElMessage.success('预约更新成功')
        } else {
          // 新增模式
          await appointmentAPI.createAppointment(form)
          ElMessage.success('预约创建成功')
        }
        
        // 返回列表页
        router.push('/appointments')
      } catch (error) {
        console.error(isEdit.value ? '更新预约失败' : '创建预约失败', error)
        ElMessage.error(error.response?.data?.message || (isEdit.value ? '更新预约失败' : '创建预约失败'))
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 跳转到创建患者页面
const goToCreatePatient = () => {
  router.push({
    path: '/patients/create',
    query: { redirect: router.currentRoute.value.fullPath }
  })
}

// 监听route query参数变化
watch(() => route.query, (query) => {
  if (query.patientId) {
    form.patientId = query.patientId
    handlePatientChange(query.patientId)
  }
}, { immediate: true })

// 页面加载时获取数据
onMounted(() => {
  getDepartments()
  
  if (isEdit.value) {
    getAppointmentDetail()
  } else {
    // 如果是从患者页面跳转过来，会带有patientId参数
    if (route.query.patientId) {
      form.patientId = route.query.patientId
      handlePatientChange(route.query.patientId)
    }
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-tips {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.option-content {
  display: flex;
  flex-direction: column;
}

.option-secondary {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}
</style> 